package com.example.http.sczw.service.impl;

import com.example.http.sczw.service.ForwardSczwRequestProxyService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouxl
 * @DATE 2021/8/31
 * @descriptoin
 */
@Component
public class ForwardSczwRequestProxyServiceImpl implements ForwardSczwRequestProxyService {


    @Override
    public String forwardSczwLoginInfo(HttpServletRequest request) throws IOException, URISyntaxException {
        return getUserInfo(request);
    }

    @Override
    public String nginxProxySczwLoginInfo(HttpServletRequest request) throws URISyntaxException, IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder(NGINX_PROXY_URL);
        HttpGet get = new HttpGet(uriBuilder.build());
        get.addHeader("Cookie",getCookieInfo(request.getCookies()));
        CloseableHttpResponse execute = client.execute(get);
        HttpEntity entity = execute.getEntity();
        return EntityUtils.toString(entity);
    }

    private String getUserInfo(HttpServletRequest request) throws URISyntaxException, IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder(SCZW_GETUSERINFOR_URL);
        HttpGet get = new HttpGet(uriBuilder.build());
        get.addHeader("Cookie",getCookieInfo(request.getCookies()));
        CloseableHttpResponse execute = client.execute(get);
        HttpEntity entity = execute.getEntity();
        return EntityUtils.toString(entity);
    }

    private String getCookieInfo(Cookie[] cookies){
        List<String> list = new ArrayList<>();
        for (Cookie cookie : cookies) {
            list.add(cookie.getName()+"="+cookie.getValue());
        }
        return String.join(";",list);
    }

}
